package com.linewell.desk.quest.area;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class AreaService implements InitializingBean {

	@Value("${quest.area.data.path}")
	private String dataPath;

	/**
	 * @param mobile 手机号
	 * @return 返回的地区，如果未查到，返回null
	 */
	public Area getArea(String mobile) {


		String queprefix =mobile.substring(0,6);

		Integer int_queprefix = Integer.parseInt(queprefix);

		AreaService areaService = new AreaService();

		List<String> txtFiletoList = areaService.readTxtFiletoList(dataPath);

		String quearea = txtFiletoList.get(int_queprefix);

		String[] split = quearea.split(" ");
		String prefix = split[0];
		Integer int_prefix = Integer.parseInt(prefix);
		String code = split[1];
		Integer short_code = Integer.parseInt(code);
		String name = split[2];
		Area area = new Area();
		area.setPrefix(int_prefix);
		area.setCode(short_code);
		area.setName(name);
       if (area!=null){
       	return area;
	   }

		return null;
	}

	/**
	 *
	 * @param dataPath
	 * @return List<String>
	 * 读取txt文本存储到集合中
	 */
	public   List<String> readTxtFiletoList(String  dataPath) {
		File file = new File(dataPath);
		//判断文件存在并且是文件
		Boolean boo = file.exists()&&file.isFile();
		System.out.println(boo);
		if (boo) {
			BufferedReader bufferedReader = null;
			try {
				//构造一个BufferedReader类来读取文件
				bufferedReader = new BufferedReader(new FileReader(file));
				String linetxt = null;
				//result用来存储文件内容
				StringBuilder result = new StringBuilder();
				//按使用readLine方法，一次读一行
				while ((linetxt = bufferedReader.readLine()) != null) {
					System.out.println(linetxt);
					result.append(linetxt);
				}
				//输出读出的所有数据（StringBuilder类型）
				System.out.println(result);
				//对文件内容操作
				List<String> results = new ArrayList<>();
				int prefix = 1300000;
				int num = 699998;
				System.out.println("将文件内容存入到数组中");
				for (int i = 0; i < result.length()/num; i++) {
					results.add(result.substring(prefix, prefix + num));
					prefix = prefix + num;
					System.out.println("索引： " + prefix);
				}
				return results;
			} catch (Exception e) {
				System.out.println("读取文件内容出错");
				e.printStackTrace();
			}finally {
				try {
					bufferedReader.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}

		}else{
			System.out.println("找不到指定的文件");
		}

		return null;
	}



	@Override
	public void afterPropertiesSet() throws Exception {

	}
}
